#!/bin/bash

# 设置定时备份的 cron 任务
# 使用方法: ./setup-backup-cron.sh [daily|every2days]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKUP_SCRIPT="$SCRIPT_DIR/backup-scheduled.sh"

# 检查备份脚本是否存在
if [ ! -f "$BACKUP_SCRIPT" ]; then
    echo "❌ 错误: 备份脚本不存在: $BACKUP_SCRIPT"
    exit 1
fi

# 确保备份脚本有执行权限
chmod +x "$BACKUP_SCRIPT"

# 获取用户选择的频率
FREQUENCY=${1:-"daily"}

case $FREQUENCY in
    "daily")
        CRON_SCHEDULE="0 2 * * *"  # 每天凌晨2点
        DESCRIPTION="每天凌晨2点"
        ;;
    "every2days")
        CRON_SCHEDULE="0 2 */2 * *"  # 每两天凌晨2点
        DESCRIPTION="每两天凌晨2点"
        ;;
    *)
        echo "❌ 错误: 不支持的频率 '$FREQUENCY'"
        echo "支持的选项: daily, every2days"
        exit 1
        ;;
esac

echo "🕐 设置定时备份任务..."
echo "📅 备份频率: $DESCRIPTION"
echo "📂 备份脚本: $BACKUP_SCRIPT"

# 创建 cron 任务
CRON_JOB="$CRON_SCHEDULE cd \"$(dirname "$BACKUP_SCRIPT")\" && \"$BACKUP_SCRIPT\" >> \"$(dirname "$BACKUP_SCRIPT")/../logs/cron.log\" 2>&1"

echo "📝 Cron 任务内容:"
echo "$CRON_JOB"
echo ""

# 检查是否已存在相同的 cron 任务
if crontab -l 2>/dev/null | grep -F "$BACKUP_SCRIPT" >/dev/null; then
    echo "⚠️  检测到已存在的备份任务，是否要替换？ (y/N)"
    read -r response
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        echo "❌ 取消设置"
        exit 0
    fi
    
    # 删除旧的备份任务
    crontab -l 2>/dev/null | grep -v "$BACKUP_SCRIPT" | crontab -
    echo "🗑️  已删除旧的备份任务"
fi

# 添加新的 cron 任务
(crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -

echo "✅ 定时备份任务设置成功！"
echo "📋 当前的 cron 任务:"
crontab -l | grep "$BACKUP_SCRIPT" || echo "未找到相关任务"

echo ""
echo "📖 使用说明:"
echo "• 查看 cron 任务: crontab -l"
echo "• 编辑 cron 任务: crontab -e"
echo "• 删除所有 cron 任务: crontab -r"
echo "• 查看备份日志: tail -f $(dirname "$BACKUP_SCRIPT")/../logs/backup_$(date +%Y%m).log"
echo "• 查看 cron 日志: tail -f $(dirname "$BACKUP_SCRIPT")/../logs/cron.log"
echo "• 手动执行备份: $BACKUP_SCRIPT"

echo ""
echo "⏰ 下次备份时间: $(date -d "tomorrow 02:00" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || echo '明天凌晨2点')"
echo "📁 备份文件位置: $(dirname "$BACKUP_SCRIPT")/../backups/"

exit 0